package com.xiaoran.robot.utils;

import com.alibaba.fastjson.JSON;
import org.jsoup.Jsoup;
import org.springframework.util.StopWatch;
import org.thymeleaf.standard.processor.StandardObjectTagProcessor;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

public class MessageSender {

    private final HashMap<String, Object> requestBody = new HashMap<>();
    private ArrayList<Object> messageChain = new ArrayList<>();
    private final String baseUrl = YamlReader.instance.getValueByKey("mirai.baseHttpUrl").toString();
    private String api;
    private static String session;

    public MessageSender(String id, String type){
        if(session == null){
            session = new MiraiUtils().bindSession();
        }
        // type => group, friend
        if ("group".equals(type)) {
            this.api = "sendGroupMessage";
        } else if ("friend".equals(type)){
            this.api = "sendFriendMessage";
        }else{
            System.out.println("不被支持的消息类型");
        }
        requestBody.put("sessionKey", session);
        requestBody.put("target", id);
    }

    public void sendMessage(){
        requestBody.put("messageChain", this.messageChain);
        String jsonData = StringUtils.toJson(requestBody);
        try {
            StopWatch stopWatch = new StopWatch();
            stopWatch.start("消息发送:");
            Jsoup.connect(baseUrl + this.api)
                    .ignoreContentType(true)
                    .header("Content-Type", "application/json")
                    .requestBody(jsonData)
                    .timeout(0)
                    .post();
            stopWatch.stop();
            System.out.println("消息发送耗时"+stopWatch.getTotalTimeSeconds());
        } catch (IOException e) {
            System.out.println("消息发送失败");
            e.printStackTrace();
        }
    }

    /**
     *
     * @param content 自定义的处理类返回的结果
     */
    public MessageSender addContent(ArrayList<Object> content){
        this.messageChain = content;
        return this;
    }

}
